﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using BSS.OAuth2;
using BSS.OAuth2.Facebook;
using Db8.Data;
using Db8.DataAccess;
using System.Web.Helpers;

namespace Db8.Controllers
{
    public class AccountController : ControllerBase
    {
        private Db8Context db = new Db8Context();

        public ActionResult Login()
        {
            var authenticationProvider = DependencyResolver.Current.GetService<BSS.OAuth2.IOAuthProvider>();
            string redirectUrl = Url.Action("Authenticate", "Account", null, "http");
            string authenticationUrl = authenticationProvider.GetAuthorizationCodeRequestUrl(redirectUrl, "email,user_location,user_religion_politics");
            return new RedirectResult(authenticationUrl);
        }

        public ActionResult Authenticate(string code)
        {
            try
            {
                var authenticationProvider = DependencyResolver.Current.GetService<BSS.OAuth2.IOAuthProvider>();

                string redirectUrl = Url.Action("Authenticate", "Account", null, "http");
                string accessToken = authenticationProvider.GetAccessToken(code, redirectUrl);
                IUser user = authenticationProvider.GetUser(accessToken);
                FacebookUser fbUser = user as FacebookUser;

                string username = user.id.ToString();
                if (fbUser != null && !string.IsNullOrEmpty(fbUser.username))
                    username = fbUser.username;

                FormsAuthentication.SetAuthCookie(username, true);

                // find user, create if needed, update data
                UserManager.LogUser(user.id,
                                    username,
                                    user.email,
                                    fbUser != null ? fbUser.LastUpdatedTime : DateTime.MinValue,
                                    user.name,
                                    fbUser != null ? fbUser.first_name : user.name,
                                    fbUser != null ? fbUser.middle_name : "",
                                    fbUser != null ? fbUser.last_name : "",
                                    accessToken);

                return RedirectToAction("Index", "Home");
            }
            catch(Exception ex)
            {
                Logger.LogException(null, ex);
                ViewBag.ErrorDetails = ex.Message + ex.StackTrace;
                return View("Error");
            }
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }


        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

    }
}
